package com.xgq.drink.controller;

import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xgq.drink.annotation.RequiresRole;
import com.xgq.drink.entity.Orders;
import com.xgq.drink.entity.R;
import com.xgq.drink.service.IOrderService;
import com.xgq.drink.utils.JwtTokenUtil;
import com.xgq.drink.utils.RUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * 商家订单管理控制器
 */
@RestController
@RequestMapping("/api/brand/order")
@Tag(name = "商家订单管理", description = "商家订单管理相关接口")
public class BrandOrderController {

    @Autowired
    private IOrderService orderService;


    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    /**
     * 分页查询品牌订单
     */
    @GetMapping("/{brandId}/list")
    @RequiresRole(value = {"STORE_OWNER", "STORE_STAFF"}, brandRequired = true)
    @Operation(summary = "分页查询品牌订单", description = "根据品牌ID分页查询订单列表",
            responses = {
                    @ApiResponse(responseCode = "200", description = "查询成功",
                            content = @Content(schema = @Schema(implementation = IPage.class))),
                    @ApiResponse(responseCode = "400", description = "查询失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R getBrandOrderList(
            @PathVariable @Parameter(description = "品牌ID", required = true) Long brandId,
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Integer status) {
        try {
            IPage<Orders> orderList = orderService.getBrandOrderList(brandId, current, size, status);
            return RUtils.success("查询成功", orderList);
        } catch (Exception e) {
            return RUtils.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 商家发货
     */
    @PostMapping("/ship/{orderId}")
    @RequiresRole(value = {"STORE_OWNER", "STORE_STAFF"}, brandRequired = true)
    @Operation(summary = "商家发货", description = "商家为指定订单发货，可选上传物流单号",
            responses = {
                    @ApiResponse(responseCode = "200", description = "发货成功",
                            content = @Content(schema = @Schema(implementation = R.class))),
                    @ApiResponse(responseCode = "400", description = "发货失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R shipOrder(
            @PathVariable @Parameter(description = "订单ID", required = true) Long orderId,
            @RequestParam(required = false) String logisticsNumber,HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
            System.out.println("执行");
            System.out.println(brandId);
            Orders order2 = orderService.getById(orderId);
            System.out.println(order2);
            if (order2.getStoreId()!=brandId) {
                return RUtils.fail("该订单不属于您的品牌，无法操作");
            }
            Orders order = orderService.shipOrder(orderId, logisticsNumber);
            return RUtils.success("发货成功", order);
        } catch (Exception e) {
            return RUtils.fail("发货失败: " + e.getMessage());
        }
    }

    /**
     * 商家关闭订单
     */
    @PostMapping("/{brandId}/close/{orderId}")
    @RequiresRole(value = {"STORE_OWNER", "STORE_STAFF"}, brandRequired = true)
    @Operation(summary = "商家关闭订单", description = "商家关闭指定订单，需要提供关闭原因",
            responses = {
                    @ApiResponse(responseCode = "200", description = "关闭成功",
                            content = @Content(schema = @Schema(implementation = R.class))),
                    @ApiResponse(responseCode = "400", description = "关闭失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R closeBrandOrder(
            @PathVariable @Parameter(description = "品牌ID", required = true) Long brandId,
            @PathVariable @Parameter(description = "订单ID", required = true) Long orderId,
            @RequestParam String reason) {
        try {
            // 查询订单是否属于该品牌
            IPage<Orders> orderPage = orderService.getBrandOrderList(brandId, 1, 1, null);
            boolean orderBelongsToBrand = orderPage.getRecords().stream()
                    .anyMatch(o -> o.getOrderId().equals(orderId));
                    
            if (!orderBelongsToBrand) {
                return RUtils.fail("该订单不属于您的品牌，无法操作");
            }
            
            Orders order = orderService.closeBrandOrder(orderId, reason);
            return RUtils.success("订单关闭成功", order);
        } catch (Exception e) {
            return RUtils.fail("订单关闭失败: " + e.getMessage());
        }
    }

    /**
     * 获取指定品牌在指定时间范围内的订单数
     */
    @GetMapping("/orderCount/timeRange")
    @RequiresRole(value = {"STORE_OWNER", "STORE_STAFF"}, brandRequired = true)
    @Operation(summary = "获取指定品牌在指定时间范围内的订单数", description = "根据品牌 ID、订单状态和时间范围查询订单数",
            responses = {
                    @ApiResponse(responseCode = "200", description = "查询成功",
                            content = @Content(schema = @Schema(implementation = R.class))),
                    @ApiResponse(responseCode = "400", description = "查询失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R getOrderCountByBrandIdAndTimeRange(
            @RequestParam(required = false) LocalDateTime startTime,
            @RequestParam(required = false) LocalDateTime endTime,
            HttpServletRequest request) {
        try {
            // 从请求头中获取 token
            String token = request.getHeader("Authorization");
            Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
            Integer orderCount = orderService.getOrderCountByBrandIdAndTimeRange(brandId, startTime, endTime);
            return RUtils.success("查询成功", orderCount);
        } catch (Exception e) {
            return RUtils.fail("查询失败: " + e.getMessage());
        }
    }
    /**
     * 获取指定品牌在指定时间范围内的金额数
     */
    @GetMapping("/totalAmount/timeRange")
    @RequiresRole(value = {"STORE_OWNER", "STORE_STAFF"}, brandRequired = true)
    @Operation(summary = "获取指定品牌在指定时间范围内的成交金额", description = "根据品牌 ID、订单状态和时间范围查询成交金额",
            responses = {
                    @ApiResponse(responseCode = "200", description = "查询成功",
                            content = @Content(schema = @Schema(implementation = R.class))),
                    @ApiResponse(responseCode = "400", description = "查询失败",
                            content = @Content(schema = @Schema(implementation = R.class)))
            })
    public R getTotalAmountByBrandIdAndTimeRange(
            @RequestParam(required = false) LocalDateTime startTime,
            @RequestParam(required = false) LocalDateTime endTime,
            HttpServletRequest request) { // 添加 HttpServletRequest 参数
        try {
            // 从请求头中获取 token
            String token = request.getHeader("Authorization");
            Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
            BigDecimal totalAmount = orderService.getTotalAmountByBrandIdAndTimeRange(brandId, startTime, endTime);
            return RUtils.success("查询成功", totalAmount);
        } catch (Exception e) {
            return RUtils.fail("查询失败: " + e.getMessage());
        }
    }
} 